/* =========================================================================
 *
 *   The traffic processor.
 *
 *   Development by Sedelnikov Alexander (Bigking).
 *
 * =========================================================================
 */

#include "log.h"
#include "thread.h"
#include "conf.h"
#include <time.h>


//-----------------------------------------------------------------------//
void  journal::__log__( const char *file,
                        const int   line,
                        const char *function,
                        const int   type,
                        const char *fmt, ... )
{
//return;
#define put_log( ... ) { printf(  __VA_ARGS__ ); if( fp != NULL ) { fprintf( fp, __VA_ARGS__ ); } }

    char      buffer[ 512 ],
              full_path[ 2049 ],
              stamp_str[ 128 ],
             *fname;
    ulong     maxsize = cconfig::get_log_maxsize();
    FILE     *fp = NULL;
    va_list   args;

    // --->
    ccritical_section::enter();

    if( type == LOG_ID_DEBUG )
    {
        if( !cconfig::get_log_debug() )
        {
            ccritical_section::leave();
            return;
        }
    }

    fname = (char*)cconfig::get_log_filename();
    if( fname == NULL )
        fname = (char*)LOG_FILE;
    if( maxsize == 0 )
        maxsize = 0x80000;

    fp = fopen( fname, "a" );
    if( fp != NULL )
    {
        fseek( fp, 0, 2 );

        if( ftell( fp ) > maxsize )
        {
            fclose( fp );
            fp = fopen( fname, "w" );
        }
    }

    va_start( args, fmt );
    vsprintf( buffer, fmt, args );
    va_end( args );

    stamp_str[ 0 ] = 0;

//#ifdef _WIN32
    tm       *stamp;
    time_t    t;

    t  = time( &t );
    stamp = localtime( (const time_t*)&t );

    sprintf( stamp_str, "%4ld-%02ld-%02ld %02d:%02d:%02d",
             stamp->tm_year + 1900, stamp->tm_mon + 1, stamp->tm_mday,
             stamp->tm_hour, stamp->tm_min, stamp->tm_sec );
//#else
//#endif


    switch( type )
    {
        case LOG_ID_LINE:
            put_log( "========================================================================\n" );
        break;
        case LOG_ID_MESSAGE:
            put_log( "%s Msg %s(%ld): %s\n", stamp_str, file, line, buffer );
        break;
        case LOG_ID_DEBUG:
//            put_log( ": %s\n", buffer );
            put_log( "%s DEBUG %s(%ld)->[%s]: %s\n", stamp_str, file, line, function, buffer );
        break;
        case LOG_ID_WARNING:
            put_log( "%s > Warning: %s\n", stamp_str, buffer );
        break;
        case LOG_ID_ERROR:
            put_log( "%s >> Error: %s\n", stamp_str, buffer );
        break;
        case LOG_ID_FATAL_ERROR:
            put_log( "%s >>> FATAL ERROR: %s\n", stamp_str, buffer );
        break;

        default:;
    }


    if( fp != NULL )
        fclose( fp );

    // <---
    ccritical_section::leave();
}
